package com.hotec.PROJECT_NAME.modules.cmd.interceptor;

import com.hotec.PROJECT_NAME.modules.cmd.entity.CommandLog;
import com.hotec.PROJECT_NAME.modules.cmd.service.CommandLogService;
import com.hotec.PROJECT_NAME.modules.cmd.support.Command;
import com.hotec.PROJECT_NAME.modules.cmd.support.CommandContext;
import com.hotec.PROJECT_NAME.utils.UtilsLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by ldz666 on 2022/9/14.
 */
@Slf4j
public class LogInterceptor extends AbstractCommandInterceptor {
    @Autowired
    CommandLogService commandLogService;

    @Override
    public <T> T execute(CommandContext context, Command<T> command) {
        log.debug("--- starting {} --------------------------------------------------------", command.getClass().getSimpleName());
        T result = null;
        Boolean flag = false;
        String msg="";
        CommandLog commandLog = this.createCommandLog(command);
        try {
            result = this.getNext().execute(context, command);
            flag = true;
        } catch (Exception e) {
            UtilsLog.log(this.getClass(), e);
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                if(stackTraceElement.toString().contains("hotec")){
                    msg =("执行命令出错[" + command.getClass().getSimpleName() + "]"+"\t"+e.toString()+"\t"+ stackTraceElement.toString());
                    break;
                }
            }

            throw e;
        } finally {
            commandLog.setResult(flag + "");
            commandLog.setRemark(msg);
            this.commandLogService.addToLog(commandLog);
            log.debug("--- {} finished --------------------------------------------------------", command.getClass().getSimpleName());
            log.debug("\n");
        }
        return result;
    }

    private CommandLog createCommandLog(Command command) {
        CommandLog commandLog = new CommandLog();
        commandLog.setCommandName(command.getClass().getSimpleName());
//        commandLog.setCreateBy(this.commandLogService.getCurrentAccountId(true));
        return commandLog;
    }
}
